<?php


namespace app\controller\coach;


use app\BaseController;
use app\common\ErrorCode;
use app\common\exception\ApiException;
use app\model\coach\UserCoachInviteModel;
use app\model\coach\UserCoachModel;
use app\model\coach\UserCoachPayModel;
use app\model\goods\OrderModel;
use app\model\school\SchoolModel;
use app\model\school\SchoolOrderModel;
use app\model\user\UserModel;
use app\service\config\ConfigService;
use app\service\user\CoachMoneyDetailService;
use app\service\user\PartnerMoneyRecordService;
use app\service\user\UserService;
use app\service\utils\WeiXinPayService;
use think\facade\Db;

class OrderController extends BaseController
{

    /**
     * 教学订单
     * @return \think\response\Json
     */
    public function getOrderList()
    {
        try {
            $userId = $this->request->middleware('userId');
            $userInfo = $this->request->middleware('userInfo');
            // 1待服务 2服务中 3已完成
            $type = $this->request->param('type', 0, 'int');
            $search = $this->request->param('search', '', 'trim');

            $where = [];
            $where1 = [];
            if ($userInfo['is_team_leader']) {
                $where[] = ['accept_uid', '=', $userId];
                $where1[] = ['accept_uid', '=', $userId];
            } else {
                $where[] = ['coach_id', '=', $userId];
                $where1[] = ['coach_id', '=', $userId];
            }
            if ($type == 1) {
                // 待服务
                $where[] = ['status', '=', 2];
            } else if ($type == 2) {
                // 服务中
                $where[] = ['status', 'in', [3, 6]];
            } else {
                // 已完成
                $where[] = ['status', '=', 4];
            }
            if ($search != '') {
                $where[] = ['username|mobile', 'like', "%{$search}%"];
            }
            $wait = SchoolOrderModel::where($where1)->where('status', 2)->count();
            $service = SchoolOrderModel::where($where1)->whereIn('status', [3, 6])->count();
            $over = SchoolOrderModel::where($where1)->where('status', 4)->count();
            $list = SchoolOrderModel::with(['coach','source'])
                ->where($where)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            return $this->success(['list' => $list, 'wait_service' => $wait, 'service' => $service, 'over' => $over]);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 指派教练
     * @return \think\response\Json
     */
    public function designCoach()
    {
        Db::startTrans();
        try {
            $coachId = $this->request->param('coach_id', 0, 'int');
            $id = $this->request->param('id', 0, 'int');

            $orderInfo = SchoolOrderModel::lock(true)->find($id);
            if (!$orderInfo) {
                throw new ApiException('订单不存在');
            }
            $orderInfo->coach_id = $coachId;
            $orderInfo->accept_time = time();
            $orderInfo->save();
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception);
        }
    }

    /**
     * 教练列表
     * @return \think\response\Json
     */
    public function getCoachList()
    {
        try {
            $userId = $this->request->middleware('userId');
            $list = UserCoachModel::with('school')
                ->where('pid', $userId)
                ->where('id', '<>', $userId)
                ->field('id,username,mobile,avatar,school_id,team,edu_type')
                ->select();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 教练确认到场
     * @return \think\response\Json
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function confirmOrder()
    {
        try {
            $userId = $this->request->middleware('userId');
            $id = $this->request->param('id', 0, 'int');
            $status = $this->request->param('status', 1, 'int');
            $remark = $this->request->param('remark', '', 'trim');
            if (!in_array($status, [0, 1])) {
                throw new ApiException('状态错误');
            }
            if ($status == 0 && !$remark) {
                throw new ApiException('请填写原因');
            }
            $orderInfo = SchoolOrderModel::lock(true)->find($id);
            if (!$orderInfo) {
                throw new ApiException('订单不存在');
            }
            if ($orderInfo['coach_id'] != $userId) {
                throw new ApiException('非法请求');
            }
            $orderInfo->status = $status ? SchoolOrderModel::ORDER_STUDYING : SchoolOrderModel::ORDER_CANCEL;
            $orderInfo->remark = $remark;
            $orderInfo->save();

            if ($status == 0) {
                Db::name('school_order_log')->insert([
                    'coach_id' => $userId,
                    'remark' => $remark,
                    'order_id' => $id,
                    'create_time' => time()
                ]);
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 教练完成
     * @return \think\response\Json
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function complete()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            if (!$userInfo['is_team_leader']) {
                throw new ApiException('您没有操作权限');
            }
            $id = $this->request->param('id', 0, 'int');
            $amount = $this->request->param('amount', 0, 'int');
            if ($amount <= 0) {
                throw new ApiException('请填写金额');
            }
            $openId = $userInfo['openid'];
            if (!$openId) {
                throw new ApiException('用户未授权登录', ErrorCode::SCOPE_LOGIN);
            }
            $orderInfo = SchoolOrderModel::lock(true)->find($id);
            if (!$orderInfo) {
                throw new ApiException('订单不存在');
            }
            Db::name('school_order_pay')->insert([
                'order_id' => $id,
                'amount' => $amount,
                'order_sn' => $orderInfo['order_sn'],
                'create_time' => time(),
                'update_time' => time(),
            ]);
            $weiXinPayService = new WeiXinPayService(1);
            $notifyUrl = $notifyUrl = $this->request->domain() . '/coach/notify/settlement';
            $result = $weiXinPayService->pay($orderInfo['order_sn'], $amount, $openId, $notifyUrl, '订单结算');
            return $this->success($result);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 抢单顶部信息
     * @return \think\response\Json
     */
    public function getInfo()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $data = [
                'new' => SchoolOrderModel::where('coach_id', $userInfo['id'])->where('status', 2)->count(),
                'money' => $userInfo['money'],
                'lock' => SchoolOrderModel::where('coach_id', $userInfo['id'])->whereIn('status', [3, 6])->sum('coach_amount')
            ];
            return $this->success($data);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 抢单列表
     * @return \think\response\Json
     */
    public function getRobOrderList()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $where = [];
            $where[] = ['status', '=', 1];
            $where[] = ['coach_id', '=', $userInfo['id']];
            $list = SchoolOrderModel::with(['user', 'course'])
                ->field('id,user_id,school_id,course_id,coach_id,amount,pay_time,pay_type')
                ->where($where)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();

            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 接单
     * @return bool|\think\response\Json
     */
    public function acceptOrder()
    {
        Db::startTrans();
        try {
            $userId = $this->request->middleware('userId');
            $userInfo = $this->request->middleware('userInfo');
            $isTeamLeader = $userInfo['is_team_leader'];
            $id = $this->request->param('id', 0, 'int');

            $orderInfo = SchoolOrderModel::lock(true)->find($id);
            if (!$orderInfo) {
                throw new ApiException('订单不存在');
            }
            if ($orderInfo['status'] != 2) {
                throw new ApiException('订单状态错误');
            }
            $orderInfo->coach_id = $userId;
            $orderInfo->status = SchoolOrderModel::ORDER_STUDYING;
            $orderInfo->accept_time = time();
            $orderInfo->save();
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception);
        }
    }

    /**
     * 我的历史订单
     * @return \think\response\Json
     */
    public function getHistoryOrderList()
    {
        try {
            $userId = $this->request->middleware('userId');

            $list = SchoolOrderModel::with(['user', 'course'])
                ->whereIn('status', 5)
                ->where('coach_id', $userId)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }


    /**
     * 订单详情
     * @return \think\response\Json
     */
    public function getOrderDetail()
    {
        try {
            $orderId = $this->request->param('id', 0, 'int');
            $orderInfo = SchoolOrderModel::with(['user', 'course', 'coach'])->find($orderId);
            return $this->success($orderInfo);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 进度确认
     * @return \think\response\Json
     */
    public function confirmProgress()
    {
        Db::startTrans();
        try {
            $orderId = $this->request->param('id', 0, 'int');
            $score = $this->request->param('score', 0, 'trim');
            $progress = $this->request->param('progress', 0, 'int');
            if (!in_array($progress, [1, 2, 3, 4, 5])) {
                throw new ApiException('进度错误');
            }
            $orderInfo = SchoolOrderModel::find($orderId);
            if (!$orderInfo) {
                throw new ApiException('订单不存在');
            }
            $scoreField = 'score' . $progress;
            $orderInfo->$scoreField = $score;
            $orderInfo->progress = $progress + 1;
            $field = 'score' . $progress . '_time';
            $orderInfo->$field = date('Y-m-d H:i:s');
            if ($progress == 4) {
                $orderInfo->status = 4;
                $orderInfo->complete_time = time();
                // 教练工资

                $moneyRecordService = new CoachMoneyDetailService();
                $type = CoachMoneyDetailService::SALARY;
                $title = $moneyRecordService->getTypeText($type);
                $moneyRecordService->createLog($title, $orderInfo['coach_id'], $type, $orderInfo['coach_amount'], 0, $orderInfo['order_sn']);

                // 推荐奖励
                $userService = new UserService();
                $userService->award($orderInfo['user_id'], $orderInfo['pay_amount'], $orderInfo['order_sn']);
            }
            $orderInfo->save();
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception);
        }
    }

    /**
     * 结款金额
     * @return \think\response\Json
     */
    public function getOrderTotalAmount()
    {
        try {
            $userId = $this->request->middleware('userId');
            $userInfo = $this->request->middleware('userInfo');

            $where = [];
            if ($userInfo['is_team_leader']) {
                $coachIdArr = UserCoachModel::where('pid', $userId)->column('id');
                array_push($coachIdArr, $userId);
                $where[] = ['coach_id', 'in', $coachIdArr];
            } else {
                $where[] = ['coach_id', '=', $userId];
            }
            $notPayAmount = SchoolOrderModel::where($where)->where('status', 3)->sum('coach_amount');
            $payAmount = SchoolOrderModel::where($where)->where('status', 4)->sum('coach_amount');
            return $this->success(['not_pay_amount' => $notPayAmount, 'pay_amount' => $payAmount]);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }


    /**
     * 完成订单
     * @param $id
     * @param $score
     * @param $process
     * @return bool
     * @throws ApiException
     */
    private function completeOrder($id, $score, $process)
    {

        try {
            $id = $this->request->param('id', 0, 'int');
            $score = $this->request->param('score', 0, 'int');
            $process = $this->request->param('process', 0, 'int');

            $orderInfo = SchoolOrderModel::find($id);
            if (!$orderInfo) {
                throw new ApiException('订单不存在');
            }
            // 拿证 订单完成
            $orderInfo->status = 4;
            $orderInfo->score = $score;
            $orderInfo->progress = $process;
            $orderInfo->save();


            return true;
        } catch (\Exception $exception) {
            throw new ApiException($exception->getMessage());
        }
    }

    /**
     * 创建教练
     * @return \think\response\Json
     */
    public function createCoach()
    {
        try {
            $userId = $this->request->middleware('userId');
            $userInfo = $this->request->middleware('userInfo');
            if (!$userInfo['is_team_leader']) {
                throw new ApiException('团队长才可以邀请教练');
            }

            $mobile = $this->request->param('mobile', '', 'trim');
            $name = $this->request->param('name', '', 'trim');

            $coachInfo = UserCoachModel::where('mobile', $mobile)->find();
            if (!$coachInfo) {
                throw new ApiException('邀请的教练不存在');
            }
            if ($coachInfo['pid']) {
                throw new ApiException('教练已有团队');
            }
//            $userCoachInfo = new UserCoachModel::find($info['user_id']);
//            $userCoachInfo->pid = $info['invite_user_id'];
//            $userCoachInfo->team = $inviteCoachInfo['team'];
//            $userCoachInfo->save();
//            $userCoachInviteModel = new UserCoachInviteModel();
//            $userCoachInviteModel->user_id = $coachInfo['id'];
//            $userCoachInviteModel->invite_user_id = $userId;
//            $userCoachInviteModel->status = 0;
//            $userCoachInviteModel->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 待认证列表
     * @return \think\response\Json
     */
    public function getAuthList()
    {
        try {
            $userId = $this->request->middleware('userId');
            $list = UserCoachInviteModel::where('user_id', $userId)
                ->where('status', 0)
                ->select();
            foreach ($list as &$value) {
                $inviteUserInfo = UserCoachModel::find($value['invite_user_id']);
                $value['invite_user_name'] = $inviteUserInfo['username'];
                $value['invite_user_avatar'] = $inviteUserInfo['avatar'];
                $value['invite_user_team'] = $inviteUserInfo['team'];

                $schoolInfo = SchoolModel::find($inviteUserInfo['school_id']);
                $value['invite_user_school'] = $schoolInfo['name'];
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 拒绝邀请
     * @return \think\response\Json
     */
    public function refuse()
    {
        try {
            $id = $this->request->param('id', 0, 'int');
            $info = UserCoachInviteModel::find($id);
            if (!$info) {
                throw new ApiException('非法请求');
            }
            $info->status = 2;
            $info->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 接受邀请
     * @return \think\response\Json
     */
    public function accept()
    {
        Db::startTrans();
        try {
            $id = $this->request->param('id', 0, 'int');
            $info = UserCoachInviteModel::find($id);
            if (!$info) {
                throw new ApiException('非法请求');
            }
            $info->status = 1;
            $info->save();

            $inviteCoachInfo = UserCoachModel::find($info['invite_user_id']);

            $userCoachInfo = UserCoachModel::find($info['user_id']);
            $userCoachInfo->pid = $info['invite_user_id'];
            $userCoachInfo->team = $inviteCoachInfo['team'];
            $userCoachInfo->save();
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception);
        }
    }

    /**
     * 缴纳保证金
     * @return \think\response\Json
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function pay()
    {
        try {
            $userId = $this->request->middleware('userId');
            $userInfo = $this->request->middleware('userInfo');
            $id = $this->request->param('id', 0, 'int');
            $userCoachInfo = UserCoachModel::find($id);
            if (!$userCoachInfo) {
                throw new ApiException('教练不存在');
            }
            if ($userCoachInfo['is_pay']) {
                throw new ApiException('该教练已交保证金');
            }
            $openId = $userInfo['openid'];
            if (!$openId) {
                throw new ApiException('用户未授权登录', ErrorCode::SCOPE_LOGIN);
            }
            $orderSn = createOrderSn('user_coach_pay');
            $money = ConfigService::getConfigValue('earnest_money');
            if ($money <= 0) {
                throw new ApiException('保证金错误');
            }
            $userCoachPayModel = new UserCoachPayModel();
            $userCoachPayModel->user_id = $id;
            $userCoachPayModel->pay_user_id = $userId;
            $userCoachPayModel->order_sn = $orderSn;
            $userCoachPayModel->money = $money;
            $userCoachPayModel->save();

            $weiXinPayService = new WeiXinPayService(1);
            $notifyUrl = $notifyUrl = $this->request->domain() . '/coach/notify/notify';
            $result = $weiXinPayService->pay($orderSn, $money, $openId, $notifyUrl, '代交保证金');
            return $this->success($result);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }
}